<?php

namespace app\api\controller;

use app\admin\model\Projectact;
use app\admin\model\Projectgongsi;
use app\admin\model\Projectzixun;
use app\admin\model\yalimedia\Order;
use app\admin\model\yalimedia\Teacher;
use app\common\controller\Api;
use app\common\model\ScoreLog;
use think\Db;
use Yansongda\Pay\Exceptions\GatewayException;

class Course extends Api
{
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['test', 'test1','cate'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];

    public function cate()
    {
        if((int)input('pid') > 1){
            $map = [
                'status' => 1,
            ];
            $list = Db::table('fa_yalimedia_teacher_cate')
                ->where('pid',input('pid'))->where($map)
                ->select();
            $list = collection($list)->toArray();
            $arr = [
                'id' => input('pid'),
                'image' => '',
                'name' => '全部',
                'pid' => '',
            ];
            array_unshift($list,$arr);
        }else{

            $teacher = new Teacher();
            $list =   $teacher->where(area_ids())->select();
            $ids = array_column($list,'cate_id');

            $list2 = Projectgongsi::where(area_ids())->select();
            $ids2 = array_column($list2,'cate_id');
            $sonids3 = array_merge($ids,$ids2);
            $map = [
                'status' => 1,
            ];
            $list3 = Db::table('fa_yalimedia_teacher_cate')
                ->where('id','in',$sonids3)
                ->where($map)
                ->select();
            $list = [];
            //if($list3){
                $list = Db::table('fa_yalimedia_teacher_cate')->where('pid',0)
                    //->where('id','in',array_column($list3,'pid'))
                    ->where($map)
                    ->select();
            //}
            $area_id2 = request()->header('areaid');
            if(empty($area_id2) && empty($list)){
                $list = Db::table('fa_yalimedia_teacher_cate')->where('pid',0)->where('status','1')->select();
            }
        }
        foreach ($list as &$v){
            $v['image'] = cdnurl($v['image'],'');
        }
        $this->success('成功',$list);
    }

    public function detail()
    {
        $map = [
            'id'=> input('id'),
        ];
        $course = Db::table('fa_yalimedia_course')
            ->where($map)->find();
        if(!$course){
            $this->error('课程错误');
        }
        $course['cover'] = cdnurl( $course['cover'],true);
        $map = [
            'user_id' => $this->auth->id,
            'item_id' => input('id'),
            'pay_status' => 1,
        ];
        $order = Db::table('fa_yalimedia_order')->where($map)->find();
        $course['is_buy'] = $order?1:0;
        $map = [
            'course_id' => input('id'),
        ];
        $list = Db::table('fa_yalimedia_course_content')
            ->where($map)
            ->select();
        $list = collection($list)->toArray();
        foreach ($list as &$v){
            $v['media_cover'] = cdnurl($v['media_cover'],true);
        }
        $data = [
            'course'  => $course,
            'list'  => $list,
        ];
        $this->success('成功',$data);
    }

    /**
     * 购买课程
     */
    public function buy(){
        $id = $this->request->post('id');
        $course = new \addons\yalimedia\service\Course();
        $courseInfo = $course->getCourseInfo($id,$this->auth->id);
        if(empty($courseInfo)){
            $this->error($course->error);
        }
        $course = new \addons\yalimedia\service\Tool();
        $order_no = $course->create_sn();

        $orderModel = new Order();
        $puser_id = 0;
        if(input('p_mobile')){
            $puser = \app\admin\model\User::where('mobile',input('p_mobile'))->find();
            if($puser){
                $puser_id = $puser['id'];
            }
        }
        if($orderModel->save([
            'order_no'=>$order_no,
            'user_id'=>$this->auth->id,
            'type'=>1,
            'item_id'=>$id,
            'p_mobile' => input('p_mobile',''),
            'puser_id' => $puser_id,
            'price'=>$courseInfo['price'],
        ])){
            try {
               if(input('pay_type') == 1){
                   $auth = Db::table('fa_shopro_user_oauth')->where("user_id",$this->auth->id)->find();
                   if(!$auth){
                      $this->error('未授权用户');
                   }
                   $params = [
                       'amount'=>$courseInfo['price'],
                       'orderid'=>$order_no,
                       'type'=>"wechat",
                       'title'=>$courseInfo['title'],
                       'notifyurl'=>$this->request->domain()."/api/yalimedia/block/notifyx",
                       'returnurl'=>"",
                       'method' => "mini",
                       'openid' => "ocvDX5TRuNS8pP1v5wTm8mEJ7tN4",
                       'openid' => $auth['openid'],
                   ];
                   $result = \addons\epay\library\Service::submitOrder($params);
                   $data=[
                       'is_pay' => 0,
                       'data' => $result,
                   ];
               }else{
                   $user = $this->auth->getUser();
                   $cou = Db::table('fa_yalimedia_course')->where('id',input('id'))->find();
                   if ($user['score'] < $cou['score']){
                       $this->error("剩余积分不足以支付");
                   }
                   ScoreLog::scoreDesc($user['id'],$cou['score'],'购买'.$cou['title']);
                   $data=[
                       'is_pay' => 1,
                       'data' => [],
                   ];
                   $order = new \addons\yalimedia\service\Order();
                   $order->pay_success($order_no);
               }
            }catch (GatewayException $e){
                $this->error($e->getMessage());
            }
            $this->success('请求成功',$data);
        }else{
            $this->success('请求失败，请稍后再试');
        }
    }

    public function baoming()
    {
        $r = Projectzixun::where('id',input('act_id'))->find();
        if(!$r){
            $this->error('参数错误');
        }
        $map = [
            'user_id' => $this->auth->id,
        ];
        $r = Projectact::where($map)->find();
        if($r){
            $this->error('您已经报名，等待工作人员联系');
        }
        $data = input();
        $data['user_id'] = $this->auth->id;
        $model = new Projectact($data);
        $model->allowField(true)->save();
        $this->success('报名成功');
    }

}